// @Auth:zdl
package record

import (
	"encoding/json"
	"fmt"

	"gitee.com/sky_big/mylog"
	"github.com/gogf/gf/g/container/gmap"
	"github.com/gorilla/websocket"

	"github.com/zhongdalu/DoorValveErWang/model"
	"github.com/zhongdalu/DoorValveErWang/public"
)

var (
	Crd       *CmdRecord
	recordMap *gmap.StrAnyMap
)

func init() {
	model.SendCmdChan = make(chan model.SendCmdMode, 1000)
	recordMap = gmap.NewStrAnyMap()
}

func WsWork() {
	c, _, err := websocket.DefaultDialer.Dial(public.WebUrl, nil)
	if err != nil {
		mylog.Panic("dial:", err)
	}
	defer func() {
		c.Close()
		mylog.Panic("二网平衡websocket 连接失败")
	}()
	done := make(chan struct{})

	go func() {
		defer close(done)
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				mylog.Error("read:", err)
				return
			}
			mylog.Println(fmt.Sprintf("recv: %s", message))
			type Xyh struct {
				Xyh int `json:"xyh"`
			}
			xyh := Xyh{}
			err = json.Unmarshal(message, &xyh)
			if err != nil {
				mylog.Error(err)
				continue
			}
			switch xyh.Xyh {
			case 0:
				data := SplitMsg{}
				err := json.Unmarshal(message, &data)
				if err != nil {
					mylog.Error(err)
					continue
				}
				if recordMap.Contains(data.UUID) {
					record := recordMap.Get(data.UUID)
					recordMap.Remove(data.UUID)
					recordMap.Set(data.CmdID[0], record)
				}
			case 1:
				data := BackMsg{}
				err := json.Unmarshal(message, &data)
				if err != nil {
					mylog.Error(err)
					continue
				}
				if recordMap.Contains(data.CmdID) {
					if record, ok := recordMap.Get(data.CmdID).(*recordInfo); ok {
						public.BackMsgChan <- model.BackMsgModel{
							Errno:      data.Errno,
							Error:      data.Error,
							IsComplete: data.IsComplete,
							AddInfo:    record.AddInfo,
						}
					}
				}
			}
		}
	}()
	for {
		select {
		case <-done:
			return
		case model := <-model.SendCmdChan:
			data := model.Command
			bs, err := json.Marshal(data)
			if err != nil {
				mylog.Error(err)
			} else {
				err = c.WriteMessage(websocket.TextMessage, bs)
				if err != nil {
					mylog.Error(err)
					return
				} else {
					mylog.Println("发送给CI：" + string(bs))
					recordMap.Set(data.UUID, NewRecordInfo(data.UUID, model.AddInfo))
				}
			}
		}
	}
}
